import 'dart:ffi';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/app_menu_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/home/model/user_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/menu_config.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../msg/model/alarm_list_resp.dart';

mixin HomePageMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  bool hasThing = false;
  bool showLoading = true;
  int userDeviceCount = 0;
  MonitorData? monitorData;

  // 菜单列表
  List<AppMenuData> menuListResp = [];
  List<AppMenuData> menuList = [];

  String _savedString = '';
  String batteryImagePath = '';



  Future<void> loadSavedString() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _savedString = prefs.getString('mapChooseIcon')?? "";
    });
  }

  /// 根据设备状态获取图标
  String getDeviceIcon(int? deviceStatus) {
    if (_savedString.length > 0) {
      return 'assets/images/home/' + _savedString + '.png';
    }else {
      if (deviceStatus == 1) {
        return 'assets/images/map/car_online.png';
      } else if (deviceStatus == 2) {
        return 'assets/images/map/car_offline.png';
      } else if (deviceStatus == 3) {
        return 'assets/images/map/car_sleep.png';
      }
      return 'assets/images/map/car_shutdown.png';
    }
  }

  /// 获取菜单列表
  fetchMenuList() async {
    if (!this.mounted) {
      return;
    }
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    // 获取菜单列表
    menuList = MenuConfig.menuList;
    menuListResp = MenuConfig.menuList;
    // 过滤置顶按钮
    menuList = menuList.where((element) => element.isTop == false).toList();
    menuListResp = menuListResp.where((element) => element.isTop == false).toList();
    // 过滤菜单
    menuList = List.from(menuListResp);
    if (deviceInfo.vipService == false) {
      menuList = menuList.where((element) => element.menuCode != 'vip').toList();
    }
    if (deviceInfo.valueAddedService == false) {
      menuList = menuList.where((element) => element.menuCode != 'valueAddedService').toList();
    }
  }

  /// 根据code获取菜单
  AppMenuData? getMenuByCode(String code) {
    return menuListResp.where((element) => element.menuCode == code).firstOrNull;
  }

  /// 显示购买vip弹窗
  showBuyVipDialog() {
    hasShowRechargeDialog = true;
    ToastUtils.showBuyVip(context, () {
      var vipMenu = getMenuByCode('vip');
      if (vipMenu != null) {
        openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
      }
    }, cancelCallback: () async {
      // 设备号登录、手机号登录，直接退出到登录页面
      final userType = ref.watch(userTypeProvider);
      if (userType == UserTypeEnum.device || userType == UserTypeEnum.phone) {
        try {
          await post('/app/user/logout');
        } catch (e) {
          XLogger.error('退出登录失败: $e');
        }
        SpUtil.putBool('isLogin', false);
        // 删除用户信息
        ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
        // 删除设备信息
        ref.read(userInfoProvider.notifier).removeUserInfo();
        context.go(RouterManager.login);
      }
    });
  }

  /// 根据页面地址打开页面
  openPageByPath(String path, String menuCode) async {
    if (path.startsWith('http')) {
      await context.push('${RouterManager.web}?url=${Uri.encodeComponent(path)}');
    } else {
      print(path);
      await context.push(path);
    }
    if (menuCode == 'vip') {
      // 刷新设备信息，判断是否需要弹出充值提示
      _judgeShowVipDialogAgain();
    }
  }

  /// 判断是否需要弹出充值提示
  _judgeShowVipDialogAgain() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei != null && deviceInfo.imei!.isNotEmpty && deviceInfo.showRechargeTip == true) {
      showBuyVipDialog();
    }
  }

  /// 设备更新时间
  String getDeviceUpdateTime(DeviceInfoVO deviceInfo) {
    if (deviceInfo.isNineDevice == true) {
      // 当前时间
      var now = DateTime.now();
      return DateUtil.formatDate(now, format: 'yyyy-MM-dd HH:mm');
    } else {
      return deviceInfo.heartbeatTime ?? '无';
    }
  }

  Future<void> checkAndShowValueAddedServiceAd(BuildContext context) async {
    // ToastUtils.showValueAddedServiceAd(
    //   context,
    //   () {
    //     // 跳转到增值服务页面
    //     context.push(RouterManager.valueAddedService);
    //   },
    // );
    // return;
    var lastShownDate = SpUtil.getString('lastShownValueAddedServiceAdDate');
    String today = DateTime.now().toString().split(' ')[0];

    if (lastShownDate != today) {
      // 检查设备的增值服务按钮是否为"是"
      bool showValueAddedServiceButton = await checkValueAddedServiceButton();

      if (showValueAddedServiceButton) {
        ToastUtils.showValueAddedServiceAd(
          context,
          () {
            // 跳转到增值服务页面
            context.push(RouterManager.valueAddedService);
          },
        );
      }

      // 更新最后显示日期
      await SpUtil.putString('lastShownValueAddedServiceAdDate', today);
    }
  }

  Future<bool> checkValueAddedServiceButton() async {
    // 这里需要实现检查设备的增值服务按钮是否为"是"的逻辑
    // 返回true表示应该显示广告,false表示不应该显示
    // 这可能涉及到API调用或者本地数据检查
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    // 判断增值服务按钮是否为"是"，且秒定模式是否过期，轨迹存储是否小于7天
    if (deviceInfo.valueAddedService == true &&
        deviceInfo.isInstantModeExpired() == true &&
        deviceInfo.trackStorageDays! <= 7) {
      return true;
    }
    return false;
  }

  // 在适当的生命周期方法中调用checkAndShowValueAddedServiceAd
  // 例如:
  @override
  void initState() {
    super.initState();
    XLogger.info("initState");
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 延迟3秒后检查是否显示增值服务广告
      Future.delayed(const Duration(seconds: 3), () {
        checkAndShowValueAddedServiceAd(context);
      });
      // getMonitorData();
    });
  }

  getMonitorData() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei}, decodeType: MonitorDataResp());
    res.when(success: (MonitorDataResp resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果地址为空，则请求接口获取地址
        if (resp.data == null) {
          return;
        }
        monitorData = resp.data!;
        ref.read(monitorDataProvider.notifier).state =
            monitorData ?? MonitorData();
        setState(() {

        });
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
    });
  }
}
